import cgi
import os
import urllib.parse as pa
import urllib.request as req
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

host = ('', 9876)
auth_token = ""

class Resquest(BaseHTTPRequestHandler):

    # POST上传附件
    def do_POST(self):
        headers = self.headers.items()
        status = self.check_Token(headers)
        if status == False:
            self.data = {401: "Token Error"}
            self.send_response(401, "Authentication failed")
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(self.data).encode())
        else:
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD': 'POST',
                         'CONTENT_TYPE': self.headers['Content-Type'],
                         })

            # filename = form['myfile'].filename.split(".")
            fileData = form['myfile'].file.read()
            # uuid = form["uuid"].value
            name = form["uuid"].value
            # name = uuid + "." + filename[len(filename)-1]
            # /var/soms/newmail/server_uploadpath/
            with open("%s" % name, "wb") as file:
                file.write(fileData)
                file.close()
            self.data = {200: "Push Success"}
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(self.data).encode())

    # GET下载附件
    def do_GET(self):
        paths = self.path
        query_dict = pa.parse_qs(paths)
        for key in query_dict.keys():
            if "fileName" in key:
                fn = os.path.join("./", query_dict[key][0])  # 下载文件地址
                try:
                    resultf = open(fn, 'rb')  # 以读的形式打开下载文件
                except BaseException:
                    self.send_response(200)  # 请求下载的文件不存在返回文件不存在报文
                    self.send_header("Content-type", "text/html;charset=UTF-8")
                    self.end_headers()
                    buf = "获取扫描数据失败，请重新获取数据"
                else:
                    self.send_response(200)  # 文件存在返回状态码
                    self.send_header("Content-type", "application/octet-stream")  # 返回请求格式为"application/octet-stream"
                    self.end_headers()
                    buf = resultf.read()  # 读取文件发送给客户端
                self.wfile.write(buf)
        self.data = {404: "not found"}
        self.send_response(404)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(self.data).encode())

    # Token验证
    def check_Token(self,token_Data):
        auth_flag = False
        for name, value in token_Data:
            if name == "Authorization":
                # print("value={}, \ntoken={}".format(value, auth_token))
                if value == auth_token:
                    auth_flag = True
                    break

        return auth_flag


if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    # with open("./publish-token.txt", "r") as file:
    #     token = file.readline()
    #     if token:
    #         auth_token = str(token.replace('\n', ''))
    # if not auth_token:
    #     print("Error: auth_token is not set.")
    auth_token = "000d7265-9421-4fb6-9a15-a8f0955b4e4e"
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()
